#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from heat.common import exception
from heat.engine import clients
from heat.engine import properties
from heat.engine import resource
from heat.engine.resources.qingresources.vpc import VPC

from heat.engine.resources.qingresources import qing_utils
from heat.engine.resources.qingresources import qing_cfg



class Subnet(resource.Resource):

    PROPERTIES = (
        AVAILABILITY_ZONE, CIDR_BLOCK, VPC_ID, TAGS,
    ) = (
        'AvailabilityZone', 'CidrBlock', 'VpcId', 'Tags',
    )

    _TAG_KEYS = (
        TAG_KEY, TAG_VALUE,
    ) = (
        'Key', 'Value',
    )

    properties_schema = {
        AVAILABILITY_ZONE: properties.Schema(
            properties.Schema.STRING,
            _('Availability zone in which you want the subnet.')
        ),
        CIDR_BLOCK: properties.Schema(
            properties.Schema.STRING,
            _('CIDR block to apply to subnet.'),
            required=True
        ),
        VPC_ID: properties.Schema(
            properties.Schema.STRING,
            _('Ref structure that contains the ID of the VPC on which you '
              'want to create the subnet.'),
            required=True
        ),
        TAGS: properties.Schema(
            properties.Schema.LIST,
            schema=properties.Schema(
                properties.Schema.MAP,
                _('List of tags to attach to this resource.'),
                schema={
                    TAG_KEY: properties.Schema(
                        properties.Schema.STRING,
                        required=True
                    ),
                    TAG_VALUE: properties.Schema(
                        properties.Schema.STRING,
                        required=True
                    ),
                },
                implemented=False,
            )
        ),
    }

    def handle_create(self):
        # TODO(sbaker) Verify that this CidrBlock is within the vpc CidrBlock
        # we assume each time only create 1 subnet
        network_id = self.properties.get(self.VPC_ID)

        iaas = qing_utils.CloudIaas()
        rets = iaas.create_vxnets(self.physical_resource_name())
        if rets[0]  != 0:
            raise exception.error(_("create subnet failed"))
            return

        ip = self.properties.get(self.CIDR_BLOCK)
        subnet= rets[1]
        print('------------------  1 ---------------------')
        print(network_id)
        router = VPC.router_for_vpc(None, network_id)
        if router:
            print(' --------------- 2 ------------------')
            print(subnet)
            print(router)
            print(ip)
            #TBD:
            import time
            time.sleep(20)
            rets = iaas.join_router(subnet[0], router, ip)
            if rets[0] != 0:
                raise exception.error(_("subnet %s join to vpc %s failed") %(subnet, router))
                return
            
        self.resource_id_set(subnet[0])

    def handle_delete(self):
        subnet_id = self.resource_id
        network_id = self.properties.get(self.VPC_ID)
        router = VPC.router_for_vpc(self.neutron(), network_id)
        
        iaas = qing_utils.CloudIaas()
        rets = iaas.leave_router(subnet_id, router)
        if rets[0] != 0:
            raise exception.error(_("subnet %s leave vpc %s failed") %(subnet_id, router))
            return
        
        rets = iaas.delete_vxnets(network_id)
        if rets[0] != 0:
            raise exception.error(_("delete subnet  %s failed ") %subnet_id)

    def FnGetAtt(self, key):
        if key == 'AvailabilityZone':
            return self.properties.get(key)
        raise exception.InvalidTemplateAttribute(resource=self.name, key=key)


def resource_mapping():
    if clients.neutronclient is None:
        return {}

    return {
        'Heat::Qing::Subnet': Subnet,
    }
